#include <func.h>

#define PAGE_SIZE 4096

int main(int argc, char* argv[])
{
    if(argc != 3)
        error(1, errno, "Usage: %s src dst", argv[0]);

    int src_fd = open(argv[1], O_RDONLY);
    if(src_fd == -1)
        error(1, errno, "open %s failed", argv[1]);
    int dst_fd = open(argv[2], O_RDWR | O_CREAT | O_TRUNC, 0666);
    if(dst_fd == -1)
        error(1, errno, "open %s failed", argv[2]);

    struct stat statbuf;
    if(fstat(src_fd, &statbuf) == -1)
        error(1, errno, "fstat");

    off_t size = statbuf.st_size;
    ftruncate(dst_fd, size);
    char buffer[4096];
    int start = 0; // 已经复制的字节数
    int count = PAGE_SIZE;
    while(start < size)
    {

        if(size - start < PAGE_SIZE)
            count = size - start;
        if(read(src_fd, buffer, count) == -1)
            error(1, errno, "read");
        if(write(dst_fd, buffer, count) == -1)
            error(1, errno, "write");

        start += count;
    }


    close(src_fd);
    close(dst_fd);

    return 0;
}

